package com.taptech.doufu.db.noveledit;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.taptech.doufu.bean.NovelEditModel;
import com.taptech.doufu.bean.NovelUploadBackupGsonBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class NovelEditDBUtil {

    private NovelEditDBHelper helper;

    public NovelEditDBUtil(Context context) {
        helper = new NovelEditDBHelper(context);
    }


    /**
     * 插入单个数据
     * @param model
     */
    public long insertSingleData(NovelEditModel model) {
        synchronized (NovelEditDBUtil.class) {
            if (model == null) {
                return model.getId();
            }
            if (TextUtils.isEmpty(model.getTitle()) &&
                    TextUtils.isEmpty(model.getContent()) &&
                    TextUtils.isEmpty(model.getAuthor_say())){
                return model.getId();
            }
            SQLiteDatabase db = helper.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put("novel_id",model.getNovel_id());
            contentValues.put("chapter_id",model.getChapter_id());
            contentValues.put("chapter_title",model.getTitle());
            contentValues.put("chapter_content",model.getContent());
            contentValues.put("chapter_flag",model.getFlag());
            contentValues.put("chapter_state",model.getState());
            contentValues.put("created_at",model.getCreated_at());
            contentValues.put("novel_author_say",model.getAuthor_say());
            contentValues.put("uid",model.getUid());
            long id = db.insert(NovelEditDBHelper.TABLE_NAME,null,contentValues);
            db.close();
            return id;
        }
    }


    public void updateSingleData(NovelEditModel model,long dbId) {
        synchronized (NovelEditDBUtil.class) {
            if (model == null) {
                return;
            }
            if (TextUtils.isEmpty(model.getTitle()) &&
                    TextUtils.isEmpty(model.getContent()) &&
                    TextUtils.isEmpty(model.getAuthor_say())){
                return;
            }
            SQLiteDatabase db = helper.getWritableDatabase();
            //更新数据
            db.execSQL("UPDATE " + NovelEditDBHelper.TABLE_NAME
                            + " SET chapter_title = ? ,chapter_content = ?,novel_author_say = ?,created_at = ? WHERE " + "_ID = ?",
                    new Object[] { model.getTitle(), model.getContent(),model.getAuthor_say(),model.getCreated_at(),dbId});
            db.close();
        }
    }

    /**
     * 插入或者更新临时数据，防止编辑过程中应用崩溃导致数据丢失
     * @param model
     */
    public long insertOrUpdateTempData(NovelEditModel model) {
        synchronized (NovelEditDBUtil.class) {
            if (model == null) {
                return 0;
            }
            if (TextUtils.isEmpty(model.getTitle()) &&
                    TextUtils.isEmpty(model.getContent()) &&
                    TextUtils.isEmpty(model.getAuthor_say())){
                return model.getTempDbId();
            }
            SQLiteDatabase db = helper.getWritableDatabase();
            String sql = "SELECT count(*) FROM "+NovelEditDBHelper.TABLE_NAME+" WHERE novel_id = "+model.getNovel_id() +" AND chapter_id = "+model.getChapter_id()+" AND chapter_state = 1";
            Cursor c = db.rawQuery(sql , null);
            c.moveToNext();
            long count = c.getLong(0);
            long id = model.getTempDbId();
            if (count>0) {
                //更新数据
                db.execSQL("UPDATE " + NovelEditDBHelper.TABLE_NAME
                                + " SET chapter_title = ? ,chapter_content = ?,novel_author_say = ?,created_at = ? WHERE " +
                                "novel_id = ? AND chapter_id = ? AND chapter_state = ?",
                        new Object[] { model.getTitle(), model.getContent(),model.getAuthor_say(),model.getCreated_at(),model.getNovel_id(),model.getChapter_id(),1 });

            }else{
                ContentValues contentValues = new ContentValues();
                contentValues.put("novel_id",model.getNovel_id());
                contentValues.put("chapter_id",model.getChapter_id());
                contentValues.put("chapter_title",model.getTitle());
                contentValues.put("chapter_content",model.getContent());
                contentValues.put("chapter_flag",model.getFlag());
                contentValues.put("chapter_state",model.getState());
                contentValues.put("created_at",model.getCreated_at());
                contentValues.put("novel_author_say",model.getAuthor_say());
                contentValues.put("uid",model.getUid());
                id = db.insert(NovelEditDBHelper.TABLE_NAME,null,contentValues);
            }
            c.close();
            db.close();
            return id;
        }
    }


    /**
     * 批量插入
     * @param list
     */
    public void insertAllData(List<NovelEditModel> list) {
        synchronized (NovelEditDBUtil.class) {
            SQLiteDatabase db = helper.getWritableDatabase();
            try {
                db.beginTransaction();
                for (NovelEditModel model:list) {
                    if (model == null) {
                        continue;
                    }
                    if (TextUtils.isEmpty(model.getTitle()) &&
                            TextUtils.isEmpty(model.getContent()) &&
                            TextUtils.isEmpty(model.getAuthor_say())){
                        continue;
                    }
                    db.execSQL(
                            "INSERT INTO "
                                    + NovelEditDBHelper.TABLE_NAME
                                    + " (novel_id,chapter_id,chapter_title,chapter_content,chapter_flag,chapter_state,created_at,novel_author_say,uid) VALUES (?,?,?,?,?,?,?,?,?)",
                            new Object[] { model.getNovel_id(), model.getChapter_id(), model.getTitle(),model.getContent(),model.getFlag(),model.getState(),model.getCreated_at(),
                                    model.getAuthor_say(),model.getUid()});
                }
                db.setTransactionSuccessful();
            }catch (Exception e){

            }finally {
                db.endTransaction();
                db.close();
            }
        }
    }


    /**
     * 根据章节ID删除数据
     * @param novelId
     * @param chapterId
     */
    public void deleteByChapterId(String novelId,String chapterId) {
        synchronized (NovelEditDBUtil.class) {
            SQLiteDatabase db = helper.getWritableDatabase();
            db.execSQL("DELETE FROM " + NovelEditDBHelper.TABLE_NAME + " WHERE novel_id = ? AND chapter_id = ?",
                    new Object[] { novelId,chapterId });
            db.close();
        }
    }


    public void deleteById(long id) {
        synchronized (NovelEditDBUtil.class) {
            SQLiteDatabase db = helper.getWritableDatabase();
            db.execSQL("DELETE FROM " + NovelEditDBHelper.TABLE_NAME + " WHERE _ID = ?",
                    new Object[] {id});
            db.close();
        }
    }


    /**
     * 清除对应的数据
     */
    public void deletePartData(List<NovelUploadBackupGsonBean.NovelBackupRes> list) {
        synchronized (NovelEditDBUtil.class) {
            SQLiteDatabase db = helper.getWritableDatabase();
            for (int i = 0; i < list.size(); i++) {
                NovelUploadBackupGsonBean.NovelBackupRes model = list.get(i);
                if (model.getDbID() > 0) {
                    db.execSQL("DELETE FROM " + NovelEditDBHelper.TABLE_NAME + " WHERE _ID = ?",
                            new Object[] {model.getDbID()});
                }
            }
            db.close();
        }
    }


    /**
     * 是否存在本地数据未同步
     * @return
     */
    public boolean hasLocalData(String uid) {
        synchronized (NovelEditDBUtil.class) {
            SQLiteDatabase db = helper.getWritableDatabase();
            String sql = "SELECT count(*) FROM "+NovelEditDBHelper.TABLE_NAME+" WHERE uid = " +uid;
            Cursor c = db.rawQuery(sql , null);
            c.moveToNext();
            long count = c.getLong(0);
            c.close();
            db.close();
            if (count > 0) {
                return true;
            }else{
                return false;
            }
        }
    }


    public List<NovelEditModel> getListByChapterId(String novelId,String chapterId){
        String sql = "SELECT * FROM "+NovelEditDBHelper.TABLE_NAME + " WHERE novel_id = " + novelId+
                " AND chapter_id = " +chapterId + " ORDER BY created_at DESC";
        return getNovelList(sql);
    }



    public List<NovelEditModel> getAllListByUid(String uid){
        String sql = "SELECT * FROM "+NovelEditDBHelper.TABLE_NAME+" WHERE uid = "+uid;
        return getNovelList(sql);
    }

    private List<NovelEditModel> getNovelList(String sql) {
        synchronized (NovelEditDBUtil.class) {
            List<NovelEditModel> list = new ArrayList<>();
            SQLiteDatabase db = helper.getReadableDatabase();
            Cursor c = db.rawQuery(sql , null);
            while (c.moveToNext()) {
                NovelEditModel model = new NovelEditModel();
                model.setId(c.getInt(c.getColumnIndex("_ID")));
                model.setNovel_id(c.getString(c.getColumnIndex("novel_id")));
                model.setChapter_id(c.getString(c.getColumnIndex("chapter_id")));
                model.setTitle(c.getString(c.getColumnIndex("chapter_title")));
                model.setContent(c.getString(c.getColumnIndex("chapter_content")));
                model.setAuthor_say(c.getString(c.getColumnIndex("novel_author_say")));
                model.setCreated_at(c.getLong(c.getColumnIndex("created_at")));
                model.setFlag(c.getInt(c.getColumnIndex("chapter_flag")));
                model.setUid(c.getString(c.getColumnIndex("uid")));
                list.add(model);
            }
            c.close();
            db.close();
            return list;
        }
    }


    public HashMap getNovelIDMap(String novelID) {
        synchronized (NovelEditDBUtil.class) {
            String sql = "SELECT chapter_id FROM "+NovelEditDBHelper.TABLE_NAME +" WHERE novel_id = "+novelID;
            HashMap<String, String> map = new HashMap<>();
            SQLiteDatabase db = helper.getReadableDatabase();
            Cursor c = db.rawQuery(sql , null);
            while (c.moveToNext()) {
                String chapter_id = c.getString(c.getColumnIndex("chapter_id"));
                if (!TextUtils.isEmpty(chapter_id)) {
                    map.put(chapter_id, chapter_id);
                }
            }
            c.close();
            db.close();
            return map;
        }
    }

}
